import {Component, OnInit} from '@angular/core';
import {
    FormBuilder,
    FormGroup,
    Validators
} from '@angular/forms';
import {HttpService} from "../../service/http.service";
import {Router} from "@angular/router";
@Component({
    selector: 'app-login',
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.less'],
})
export class LoginComponent implements OnInit {
    validateForm: FormGroup;
    constructor(private fb: FormBuilder, private http: HttpService,public router:Router) {
    }
    _submitForm($event, validateForm) {
        for (const i in this.validateForm.controls) {
            this.validateForm.controls[i].markAsDirty();
        }
        $event.preventDefault();
        // console.log(validateForm.value)
        let value = validateForm.value;
        this.http.login(value).subscribe(res => {
            console.log(`res ------> `,res)
            if (res.code !== 0) {
                //手动触发表单验证错误
                this.validateForm.controls['username'].setErrors({userNotExits: true});
            }
            else {
                //this.loginForm.controls['username'].setErrors(null);
                this.router.navigateByUrl('/home');
            }
        });
    }



    ngOnInit() {
        this.validateForm = this.fb.group({
            username: ['', [Validators.required]],
            password: ['', [Validators.required]],
            remember: [true],
        });
    }
}
